import { watch } from "vue";
import { useChatWS } from "@/composables/useChatWS";
import { pushEventByText } from "@/composables/useAudioWS";
import { useStore } from "@/stores/data";

const MAP_GAP_KEY: Record<string, keyof ReturnType<typeof useStore>["userConfig"]> = {
  welcome:  "welcomeSpace" as any,
  like:     "likeTxtSpace" as any,
  gift:     "giftTxtSpace" as any,
  follow:   "loveTxtSpace" as any,
  chat:     "dsSpace" as any,
  interrupt:"dsSpace" as any,
};

function toPair(e:any): {qtype:string, text:string} | null {
  const et = String(e?.type||e?.method||"").toLowerCase();
  if (et==="like"||et==="webcastlikemessage"){
    const u=e.user_name||e.user||""; const c=e.count||e.like_count||1; return {qtype:"like", text:`感谢 ${u} 点了 ${c} 个赞！`};
  }
  if (et==="gift"||et==="webcastgiftmessage"){
    const u=e.user_name||e.user||""; const g=e.gift_name||e.gift||"礼物"; const c=e.gift_cnt||e.count||1; return {qtype:"gift", text:`感谢 ${u} 送出 ${g} × ${c}！`};
  }
  if (et==="welcome"||et==="member_enter"||et==="webcastmembermessage"){
    const u=e.user_name||e.user||""; return {qtype:"welcome", text:`欢迎 ${u} 进入直播间～`};
  }
  if (et==="follow"||et==="webcastsocialmessage"){
    const u=e.user_name||e.user||""; return {qtype:"follow", text:`感谢 ${u} 的关注！`};
  }
  if (et==="chat"||et==="webcastchatmessage"){
    const u=e.user_name||e.user||""; const t=(e.content||"").trim(); if(!t) return null;
    return {qtype:"interrupt", text:`${u} 说：${t}`};
  }
  return null;
}

export function useEventAutoTTS(){
  const chat = useChatWS();
  const store = useStore();
  const lastAt: Record<string, number> = {};

  watch(() => chat.lastMsg, async (m) => {
    if (!m || m.type !== "danmu_event") return;
    const pair = toPair(m.data);
    if (!pair) return;

    const key = MAP_GAP_KEY[pair.qtype] || ("dsSpace" as any);
    const gapSec = Number((store.userConfig as any)[key] ?? 0);
    const now = Date.now() / 1000;
    const last = lastAt[pair.qtype] || 0;
    if (gapSec > 0 && (now - last) < gapSec) return; // 限流
    lastAt[pair.qtype] = now;

    pushEventByText(pair.text, pair.qtype as any);
  }, { immediate: false, deep: false });
}
